<?php 
/**
 * @author Robert Hahn
 * @version 02/28/2011
 */
class SnaptwitterComponent extends Object	{
	
	var $name = 'Snaptwitter'; 
	var $components = array('Session', 'Cookie'); 
	var $options = array();
	var $user = array();
	var $endpoints = array(
						"request_token" => "https://twitter.com/oauth/request_token", 
						"authorize" => "https://twitter.com/oauth/authorize",
						"access_token" => "https://api.twitter.com/oauth/access_token",
					);
	var $oauth = array();
	
	function initialize(&$controller) {
		$this->controller = &$controller;
	}
	/**
	 * business as usual - set the options
	 * @param array $options
	 */
	function setOptions( $options=array() )	{
		if (!defined("TWITTER_APP_ID") && isset($options['appid']))
		define('TWITTER_APP_ID', $options['appid']);
		if (!defined("TWITTER_SECRET_ID") && isset($options['secretkey']))
		define('TWITTER_SECRET_ID', $options['secretkey']);
		
		if (!is_array($options)) return;
		foreach($options as $key => $value)	
			$this->options[ $key ] = $value;
	}
	
	function getRequestToken()	{
        $results = $this->makeTwitterRequest('request_token', array() );
		if (!isset($results['oauth_token']) || !isset($results['oauth_token_secret'])) $this->oauth = array();
		$this->oauth = $results;
		$this->Session->write('Twitter', $this->oauth);
		return $this->oauth;
    }
    
    function getAuthorizeUrl()	{
    	if (count($this->oauth) == 0) $this->getRequestToken();
    	return "{$this->endpoints['authorize']}?oauth_token={$this->oauth['oauth_token']}";
    }

    private function _urlencode_rfc3986($input)	{
        if (is_array($input)) {
        	foreach($input as $i => $str) $input[$i] = $this->_urlencode_rfc3986($str);
            return $input;
        }
        elseif (is_scalar($input))
            return str_replace('+',' ',str_replace('%7E', '~', rawurlencode($input)));
        return '';
	}
	
	private function makeTwitterRequest($endpoint, $params=array())	{
		$oauth = array_merge($params, 
			array(
	            "oauth_version" => "1.0",
	            "oauth_nonce" => time(),
	            "oauth_timestamp" => time(),
	            "oauth_consumer_key" => $this->options['appid'],
	            "oauth_signature_method" => "HMAC-SHA1",
			)
		);
		$endpoint = $this->endpoints[$endpoint];
		$keys = $this->_urlencode_rfc3986(array_keys($oauth));
        $values = $this->_urlencode_rfc3986(array_values($oauth));
        $oauth = array_combine($keys, $values);
        uksort($oauth, 'strcmp');
        foreach ($oauth as $k => $v) {$pairs[] = $this->_urlencode_rfc3986($k).'='.$this->_urlencode_rfc3986($v);}
        $concatenatedParams = implode('&', $pairs);
        $baseString= "GET&".$this->_urlencode_rfc3986($endpoint)."&".$this->_urlencode_rfc3986($concatenatedParams);
        $secret = "{$this->_urlencode_rfc3986($this->options['secretkey'])}&";
        $oauth['oauth_signature'] = $this->_urlencode_rfc3986(base64_encode(hash_hmac('sha1', $baseString, $secret, TRUE)));
        uksort($oauth, 'strcmp');
        foreach ($oauth as $k => $v) $urlPairs[] = "$k=$v";
        $concatenatedUrlParams = implode('&', $urlPairs);
        $url = "$endpoint?$concatenatedUrlParams";
		App::import('Core', 'HttpSocket');
		$HttpSocket = new HttpSocket();
		$oauth = explode('&', $HttpSocket->get($url));
		$results = array();
		foreach($oauth as $i => $val)	{
			list($key, $value) = explode('=', $val);
			$results[$key] = $value;
		}
		return $results;
	}
	
	/**
	 * will check if the url was called by facebook; in case the facebook user will be grabbed
	 * @return object facebook account given by the facebook oauth request with our access token
	 */
	function onLoginCallback()	{
		if (isset($this->controller->params['url']) && isset($this->controller->params['url']['oauth_token']) && isset($this->controller->params['url']['oauth_verifier']))	{
			
			$this->oauth['oauth_token'] = $this->controller->params['url']['oauth_token'];
			$this->oauth['oauth_verifier'] = $this->controller->params['url']['oauth_verifier'];
			$this->Session->write('Twitter', $this->oauth);
			
			$oauth = array(
				"oauth_verifier" => $this->oauth['oauth_verifier'],
				"oauth_token" => $this->oauth['oauth_token'],
	        );
	        $results = $this->makeTwitterRequest('access_token', $oauth );
	        if (isset($results['screen_name']) && isset($results['user_id']))	{
				return $results;
			}
		}
		return null; // ups, that wasnt a valid twitter request
	}
}
?>